home *** CD-ROM | disk | FTP | other *** search
- Path: user2.mnsinc.com!huang
- From: huang@mnsinc.com (Szu-Wen Huang)
- Newsgroups: comp.lang.c
- Subject: Re: char* still alive after free ???
- Date: 18 Apr 1996 15:09:43 GMT
- Organization: Monumental Network Systems
- Message-ID: <4l5lvn$1s4@news1.mnsinc.com>
- References: <317269EA.11BB93C2@studbox.uni-stuttgart.de>
- NNTP-Posting-Host: user.mnsinc.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- Markus Heller (Markus.Heller@studbox.uni-stuttgart.de) wrote:
-
- : I want to use it to store different "strings" (at diffreent times).
- : E.g., if I want to sore 10 characters in text, I do a
- : text=(char *) malloc(10*sizeof(char));
- : When I want to use text to store 3 other characters, I first do a
- : free(text); text=NULL; and finally a
- : text=(char *) malloc(3*sizeof(char));
- : But to my surprise there are still the 4thh to 10th charcter of
- : text contained before the free(text)/malloc... ???
- : This happens under linux, but why ?
- : (what I want to to is to get filenames from the user and then open those
- : files by a function to which I pass the file name..)
-
- This is not surprising. free() updates some internal data structure
- to tell itself that the memory allocated for text (the 10 chars) is
- now free for use, but *does not* erase its contents. The subsequent
- malloc() was given the same chunk of memory that was previously freed,
- so its contents are still there. This makes perfect sense because
- otherwise free() would be wasting its time clearing memory. If you
- needed a cleared (to zero) memory space, use calloc() instead.
-
- By the way, the "text = NULL;" is useless, because its value is
- immediately overwritten by the subsequent malloc().
-